/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package interfaz;

import Calculos.Dato;
import dbconnector.Conexion_DB;
import java.awt.Color;
import java.awt.HeadlessException;
import java.beans.Beans;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import jpa.entities.GraficaEnsayoPK;
import jpa.entities.TipoEnsayo;
import jpa.converters.DateConverter;
import jpa.converters.NumberCellRenderer;
import jpa.entities.GraficaEnsayo;
import org.jfree.chart.ChartPanel;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.event.ChartChangeEvent;
import org.jfree.chart.event.ChartChangeListener;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import reportes.Reportes;

/**
 *
 * @author innovapps.co
 */
public class TraccionForm extends JPanel {
    //Variables

    private JFreeChart chart;
    boolean booleanFluencia = false;
    String logotipo = "/reportes/logoEmpresa.jpg";
    String datoPiedeRey = "";
    float datoCeldasActual = 0, datoCeldasTemp = 0, datoPieDeRey = 0, traccion = 0, fluencia = 0;
    List<Dato> datos = new ArrayList<>();
    DecimalFormat df = new DecimalFormat("0.00");
    //Conexión Base de Datos    
    Conexion_DB db = new Conexion_DB();
    ResultSet rs = null;
    //Principal, manejo de puertos
    Principal windows;

    public TraccionForm(Principal windows) {
        this.windows = windows;
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }

        idEnsayoField.setEnabled(false);
        fechaField.setEnabled(false);
        traccionResistenciaField.setEnabled(false);
        fluenciaResistenciaField.setEnabled(false);
        normaIdNormaFluenciaField.setEnabled(false);
        normaIdNormaTraccionField.setEnabled(false);
        jTextFieldLeerPieDeRey.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("TraccionJPAPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT e FROM Ensayo e WHERE e.tipoEnsayoIdTipoEnsayo = :tipoEnsayo");
       query.setParameter("tipoEnsayo", new TipoEnsayo((short) 1));
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        clienteQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Cliente c");
        clienteList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clienteQuery.getResultList();
        laboratoristaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT l FROM Laboratorista l");
        laboratoristaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : laboratoristaQuery.getResultList();
       diametroNominalQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT d FROM DiametroNominal d WHERE d.tipoEnsayo = :tipoEnsayo");
	diametroNominalQuery.setParameter("tipoEnsayo", "Tracción");
	diametroNominalList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : diametroNominalQuery.getResultList();
        certificacionQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Certificacion c");
        certificacionList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : certificacionQuery.getResultList();
        graficaEnsayoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT g FROM GraficaEnsayo g");
        graficaEnsayoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : graficaEnsayoQuery.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        idEnsayoLabel = new javax.swing.JLabel();
        fechaLabel = new javax.swing.JLabel();
        obraLabel = new javax.swing.JLabel();
        clienteIdClienteLabel = new javax.swing.JLabel();
        laboratoristaIdLaboratoristaLabel = new javax.swing.JLabel();
        diametroNominalIdDiametroNominalLabel = new javax.swing.JLabel();
        longitudLabel = new javax.swing.JLabel();
        certificacionIdCertificacionLabel = new javax.swing.JLabel();
        elongacionPorcentajeLabel = new javax.swing.JLabel();
        traccionResistenciaLabel = new javax.swing.JLabel();
        fluenciaResistenciaLabel = new javax.swing.JLabel();
        detalleIdDetalleLabel = new javax.swing.JLabel();
        normaIdNormaTraccionLabel = new javax.swing.JLabel();
        normaIdNormaFluenciaLabel = new javax.swing.JLabel();
        idEnsayoField = new javax.swing.JTextField();
        fechaField = new javax.swing.JTextField();
        obraField = new javax.swing.JTextField();
        longitudField = new javax.swing.JTextField();
        elongacionPorcentajeField = new javax.swing.JTextField();
        traccionResistenciaField = new javax.swing.JTextField();
        fluenciaResistenciaField = new javax.swing.JTextField();
        normaIdNormaTraccionField = new javax.swing.JTextField();
        normaIdNormaFluenciaField = new javax.swing.JTextField();
        jPanelGrafica = new javax.swing.JPanel();
        jPanelControles = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableCeldasPie = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableGrafico = new javax.swing.JTable();
        jComboBoxCliente = new javax.swing.JComboBox();
        jComboBoxLaboratorista = new javax.swing.JComboBox();
        jComboBoxDiametro = new javax.swing.JComboBox();
        jComboBoxCertificacion = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();
        jLabel17 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        cboxPorts = new javax.swing.JComboBox();
        cboxPorts1 = new javax.swing.JComboBox();
        jTextFieldLeerPieDeRey = new javax.swing.JTextField();
        btnConnect = new javax.swing.JButton();
        jButtonDetener = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        jButtonImprimir = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        detalleField = new javax.swing.JTextField();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idEnsayo}"));
        columnBinding.setColumnName("Id Ensayo");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fecha}"));
        columnBinding.setColumnName("Fecha");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${clienteIdCliente}"));
        columnBinding.setColumnName("Cliente Id Cliente");
        columnBinding.setColumnClass(jpa.entities.Cliente.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${diametroNominalIdDiametroNominal}"));
        columnBinding.setColumnName("Diametro Nominal Id Diametro Nominal");
        columnBinding.setColumnClass(jpa.entities.DiametroNominal.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${longitud}"));
        columnBinding.setColumnName("Longitud");
        columnBinding.setColumnClass(Float.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${elongacionPorcentaje}"));
        columnBinding.setColumnName("Elongacion Porcentaje");
        columnBinding.setColumnClass(Float.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${traccionResistencia}"));
        columnBinding.setColumnName("Traccion Resistencia");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fluenciaResistencia}"));
        columnBinding.setColumnName("Fluencia Resistencia");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);

        idEnsayoLabel.setText("Ensayo:");

        fechaLabel.setText("Fecha:");

        obraLabel.setText("Obra:");

        clienteIdClienteLabel.setText("Cliente:*");

        laboratoristaIdLaboratoristaLabel.setText("Laboratorista:*");

        diametroNominalIdDiametroNominalLabel.setText("Diametro Nominal:*");

        longitudLabel.setText("Longitud:*");

        certificacionIdCertificacionLabel.setText("Certificacion:*");

        elongacionPorcentajeLabel.setText("Elongacion Porcentaje:*");

        traccionResistenciaLabel.setText("Traccion Resistencia:");

        fluenciaResistenciaLabel.setText("Fluencia Resistencia:");

        detalleIdDetalleLabel.setText("Colada/Lote:*");

        normaIdNormaTraccionLabel.setText("Norma Traccion:");

        normaIdNormaFluenciaLabel.setText("Norma Fluencia:");

        idEnsayoField.setEditable(false);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.idEnsayo}"), idEnsayoField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        bindingGroup.addBinding(binding);

        fechaField.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.fecha}"), fechaField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        binding.setConverter(new DateConverter());
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.obra}"), obraField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), obraField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.longitud}"), longitudField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), longitudField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        longitudField.addKeyListener(formListener);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.elongacionPorcentaje}"), elongacionPorcentajeField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${false}"), elongacionPorcentajeField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        elongacionPorcentajeField.addKeyListener(formListener);

        traccionResistenciaField.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.traccionResistencia}"), traccionResistenciaField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        bindingGroup.addBinding(binding);

        fluenciaResistenciaField.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.fluenciaResistencia}"), fluenciaResistenciaField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        bindingGroup.addBinding(binding);

        normaIdNormaTraccionField.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.normaIdNormaTraccion.valor}"), normaIdNormaTraccionField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        bindingGroup.addBinding(binding);

        normaIdNormaFluenciaField.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.normaIdNormaFluencia.valor}"), normaIdNormaFluenciaField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue("null");
        bindingGroup.addBinding(binding);

        javax.swing.GroupLayout jPanelGraficaLayout = new javax.swing.GroupLayout(jPanelGrafica);
        jPanelGrafica.setLayout(jPanelGraficaLayout);
        jPanelGraficaLayout.setHorizontalGroup(
            jPanelGraficaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanelGraficaLayout.setVerticalGroup(
            jPanelGraficaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jTableCeldasPie.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Celdas", "Pie de Rey"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableCeldasPie.setEnabled(false);
        jTableCeldasPie.setFocusable(false);
        jScrollPane1.setViewportView(jTableCeldasPie);

        jTableGrafico.setEnabled(false);
        jTableGrafico.setFocusable(false);

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${selectedElement.graficaEnsayoList}");
        jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, eLProperty, jTableGrafico);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${esfuerzo}"));
        columnBinding.setColumnName("Esfuerzo (Kg-f/mm^2)");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${deformacion}"));
        columnBinding.setColumnName("Deformación %");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane3.setViewportView(jTableGrafico);
        if (jTableGrafico.getColumnModel().getColumnCount() > 0) {
            jTableGrafico.getColumnModel().getColumn(0).setCellRenderer(new NumberCellRenderer());
	    jTableGrafico.getColumnModel().getColumn(1).setCellRenderer(new NumberCellRenderer());
        }

        javax.swing.GroupLayout jPanelControlesLayout = new javax.swing.GroupLayout(jPanelControles);
        jPanelControles.setLayout(jPanelControlesLayout);
        jPanelControlesLayout.setHorizontalGroup(
            jPanelControlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelControlesLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE))
        );
        jPanelControlesLayout.setVerticalGroup(
            jPanelControlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, clienteList, jComboBoxCliente);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.clienteIdCliente}"), jComboBoxCliente, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"), "cliente");
        bindingGroup.addBinding(binding);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, laboratoristaList, jComboBoxLaboratorista, "");
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.laboratoristaIdLaboratorista}"), jComboBoxLaboratorista, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, diametroNominalList, jComboBoxDiametro);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.diametroNominalIdDiametroNominal}"), jComboBoxDiametro, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        jComboBoxCertificacion.setFocusable(false);
        jComboBoxCertificacion.setMaximumSize(new java.awt.Dimension(344, 344));
        jComboBoxCertificacion.setRequestFocusEnabled(false);
        jComboBoxCertificacion.setVerifyInputWhenFocusTarget(false);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, certificacionList, jComboBoxCertificacion);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.certificacionIdCertificacion}"), jComboBoxCertificacion, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        txtLog.setEditable(false);
        txtLog.setColumns(20);
        txtLog.setLineWrap(true);
        txtLog.setRows(5);
        txtLog.setFocusable(false);
        jScrollPane2.setViewportView(txtLog);

        jLabel17.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel17.setText("Ensayo Resistencia a la Tracción");

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Herramientas"));
        jPanel3.setMinimumSize(new java.awt.Dimension(484, 64));

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        cboxPorts.setMinimumSize(new java.awt.Dimension(50, 20));
        cboxPorts.setPreferredSize(new java.awt.Dimension(80, 25));
        jToolBar1.add(cboxPorts);

        cboxPorts1.setMinimumSize(new java.awt.Dimension(80, 20));
        cboxPorts1.setPreferredSize(new java.awt.Dimension(80, 25));
        jToolBar1.add(cboxPorts1);

        jTextFieldLeerPieDeRey.setMaximumSize(new java.awt.Dimension(60, 25));
        jTextFieldLeerPieDeRey.setMinimumSize(new java.awt.Dimension(60, 25));
        jTextFieldLeerPieDeRey.setPreferredSize(new java.awt.Dimension(60, 25));
        jTextFieldLeerPieDeRey.addActionListener(formListener);
        jToolBar1.add(jTextFieldLeerPieDeRey);

        btnConnect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/play.png"))); // NOI18N
        btnConnect.setToolTipText("Iniciar");
        btnConnect.setMaximumSize(new java.awt.Dimension(39, 45));
        btnConnect.setMinimumSize(new java.awt.Dimension(39, 45));
        btnConnect.addActionListener(formListener);
        jToolBar1.add(btnConnect);

        jButtonDetener.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/stop.png"))); // NOI18N
        jButtonDetener.setToolTipText("Parar");
        jButtonDetener.addActionListener(formListener);
        jToolBar1.add(jButtonDetener);

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/save.png"))); // NOI18N
        saveButton.setToolTipText("Guardar");
        saveButton.setMaximumSize(new java.awt.Dimension(44, 44));
        saveButton.setMinimumSize(new java.awt.Dimension(44, 44));
        saveButton.addActionListener(formListener);
        jToolBar1.add(saveButton);

        jButtonImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/print.png"))); // NOI18N
        jButtonImprimir.setToolTipText("Imprimir");
        jButtonImprimir.setFocusable(false);
        jButtonImprimir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonImprimir.setMaximumSize(new java.awt.Dimension(44, 44));
        jButtonImprimir.setMinimumSize(new java.awt.Dimension(44, 44));
        jButtonImprimir.setPreferredSize(new java.awt.Dimension(39, 39));
        jButtonImprimir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonImprimir.addActionListener(formListener);
        jToolBar1.add(jButtonImprimir);

        newButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/new.png"))); // NOI18N
        newButton.setToolTipText("Nuevo");
        newButton.addActionListener(formListener);
        jToolBar1.add(newButton);

        refreshButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/refresh.png"))); // NOI18N
        refreshButton.setToolTipText("Refrescar");
        refreshButton.addActionListener(formListener);
        jToolBar1.add(refreshButton);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.detalle}"), detalleField, org.jdesktop.beansbinding.BeanProperty.create("text"), "detalleBind");
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), detalleField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        detalleField.addKeyListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(idEnsayoLabel)
                                    .addComponent(fechaLabel)
                                    .addComponent(obraLabel)
                                    .addComponent(clienteIdClienteLabel)
                                    .addComponent(laboratoristaIdLaboratoristaLabel)
                                    .addComponent(diametroNominalIdDiametroNominalLabel)
                                    .addComponent(longitudLabel)
                                    .addComponent(certificacionIdCertificacionLabel)
                                    .addComponent(elongacionPorcentajeLabel)
                                    .addComponent(traccionResistenciaLabel)
                                    .addComponent(fluenciaResistenciaLabel)
                                    .addComponent(detalleIdDetalleLabel)
                                    .addComponent(normaIdNormaTraccionLabel)
                                    .addComponent(normaIdNormaFluenciaLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(normaIdNormaTraccionField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(fluenciaResistenciaField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(traccionResistenciaField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(elongacionPorcentajeField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(idEnsayoField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(fechaField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(obraField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jComboBoxCliente, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jComboBoxLaboratorista, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jComboBoxDiametro, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(longitudField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(normaIdNormaFluenciaField)
                                    .addComponent(jComboBoxCertificacion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(detalleField)))
                            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanelControles, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane2)
                            .addComponent(jPanelGrafica, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(masterScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 595, Short.MAX_VALUE)))
                    .addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel17)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(idEnsayoLabel)
                            .addComponent(idEnsayoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fechaLabel)
                            .addComponent(fechaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(obraLabel)
                            .addComponent(obraField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(clienteIdClienteLabel)
                            .addComponent(jComboBoxCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(laboratoristaIdLaboratoristaLabel)
                            .addComponent(jComboBoxLaboratorista, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(diametroNominalIdDiametroNominalLabel)
                            .addComponent(jComboBoxDiametro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jPanelGrafica, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanelControles, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(longitudLabel)
                            .addComponent(longitudField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(certificacionIdCertificacionLabel)
                            .addComponent(jComboBoxCertificacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(detalleIdDetalleLabel)
                            .addComponent(detalleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(elongacionPorcentajeLabel)
                            .addComponent(elongacionPorcentajeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(traccionResistenciaLabel)
                            .addComponent(traccionResistenciaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fluenciaResistenciaLabel)
                            .addComponent(fluenciaResistenciaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(0, 0, 0)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(normaIdNormaTraccionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addComponent(normaIdNormaTraccionLabel)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(normaIdNormaFluenciaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(normaIdNormaFluenciaLabel)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(50, 50, 50))
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.KeyListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == jTextFieldLeerPieDeRey) {
                TraccionForm.this.jTextFieldLeerPieDeReyActionPerformed(evt);
            }
            else if (evt.getSource() == btnConnect) {
                TraccionForm.this.btnConnectActionPerformed(evt);
            }
            else if (evt.getSource() == jButtonDetener) {
                TraccionForm.this.jButtonDetenerActionPerformed(evt);
            }
            else if (evt.getSource() == saveButton) {
                TraccionForm.this.saveButtonActionPerformed(evt);
            }
            else if (evt.getSource() == jButtonImprimir) {
                TraccionForm.this.jButtonImprimirActionPerformed(evt);
            }
            else if (evt.getSource() == newButton) {
                TraccionForm.this.newButtonActionPerformed(evt);
            }
            else if (evt.getSource() == refreshButton) {
                TraccionForm.this.refreshButtonActionPerformed(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == longitudField) {
                TraccionForm.this.numberFieldKeyTyped(evt);
            }
            else if (evt.getSource() == elongacionPorcentajeField) {
                TraccionForm.this.numberFieldKeyTyped(evt);
            }
            else if (evt.getSource() == detalleField) {
                TraccionForm.this.detalleFieldnumberFieldKeyTyped(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                TraccionForm.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("unchecked")
    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        actualizar();
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        nuevoEnsayo();
    }//GEN-LAST:event_newButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        guardar();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void jTextFieldLeerPieDeReyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldLeerPieDeReyActionPerformed
        leerDatos();
    }//GEN-LAST:event_jTextFieldLeerPieDeReyActionPerformed

    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
        conectar();
    }//GEN-LAST:event_btnConnectActionPerformed

    private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed
        detener();
    }//GEN-LAST:event_jButtonDetenerActionPerformed

    private void numberFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_numberFieldKeyTyped
        char c = evt.getKeyChar();

        String Letra = Character.toString(c).toUpperCase();

        if (!Character.isDigit(c)) {
            if (Letra.equals(".")) {
                JTextField temp = (JTextField) evt.getComponent();
                if (temp.getText().contains(".")) {
                    getToolkit().beep();
                    evt.consume();
                }
            } else {
                getToolkit().beep();
                evt.consume();
            }
        }
    }//GEN-LAST:event_numberFieldKeyTyped

    private void jButtonImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirActionPerformed
        impresion("traccion.jasper");
    }//GEN-LAST:event_jButtonImprimirActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        renderGrafico();
    }//GEN-LAST:event_masterTableMouseClicked

    private void detalleFieldnumberFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_detalleFieldnumberFieldKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_detalleFieldnumberFieldKeyTyped
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton btnConnect;
    public javax.swing.JComboBox cboxPorts;
    public javax.swing.JComboBox cboxPorts1;
    private javax.swing.JLabel certificacionIdCertificacionLabel;
    private java.util.List<jpa.entities.Certificacion> certificacionList;
    private javax.persistence.Query certificacionQuery;
    private javax.swing.JLabel clienteIdClienteLabel;
    private java.util.List<jpa.entities.Cliente> clienteList;
    private javax.persistence.Query clienteQuery;
    private javax.swing.JTextField detalleField;
    private javax.swing.JLabel detalleIdDetalleLabel;
    private javax.swing.JLabel diametroNominalIdDiametroNominalLabel;
    private java.util.List<jpa.entities.DiametroNominal> diametroNominalList;
    private javax.persistence.Query diametroNominalQuery;
    private javax.swing.JTextField elongacionPorcentajeField;
    private javax.swing.JLabel elongacionPorcentajeLabel;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JTextField fechaField;
    private javax.swing.JLabel fechaLabel;
    private javax.swing.JTextField fluenciaResistenciaField;
    private javax.swing.JLabel fluenciaResistenciaLabel;
    private java.util.List<jpa.entities.GraficaEnsayo> graficaEnsayoList;
    private javax.persistence.Query graficaEnsayoQuery;
    private javax.swing.JTextField idEnsayoField;
    private javax.swing.JLabel idEnsayoLabel;
    private javax.swing.JButton jButtonDetener;
    private javax.swing.JButton jButtonImprimir;
    private javax.swing.JComboBox jComboBoxCertificacion;
    private javax.swing.JComboBox jComboBoxCliente;
    private javax.swing.JComboBox jComboBoxDiametro;
    private javax.swing.JComboBox jComboBoxLaboratorista;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanelControles;
    private javax.swing.JPanel jPanelGrafica;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTableCeldasPie;
    private javax.swing.JTable jTableGrafico;
    private javax.swing.JTextField jTextFieldLeerPieDeRey;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel laboratoristaIdLaboratoristaLabel;
    private java.util.List<jpa.entities.Laboratorista> laboratoristaList;
    private javax.persistence.Query laboratoristaQuery;
    private java.util.List<jpa.entities.Ensayo> list;
    private javax.swing.JTextField longitudField;
    private javax.swing.JLabel longitudLabel;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newButton;
    private javax.swing.JTextField normaIdNormaFluenciaField;
    private javax.swing.JLabel normaIdNormaFluenciaLabel;
    private javax.swing.JTextField normaIdNormaTraccionField;
    private javax.swing.JLabel normaIdNormaTraccionLabel;
    private javax.swing.JTextField obraField;
    private javax.swing.JLabel obraLabel;
    private javax.persistence.Query query;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField traccionResistenciaField;
    private javax.swing.JLabel traccionResistenciaLabel;
    public javax.swing.JTextArea txtLog;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public void nuevoEnsayo() {
        booleanFluencia = false;
        jpa.entities.Ensayo e = new jpa.entities.Ensayo();
        javax.persistence.Query normaQueryFluencia = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT n FROM Norma n WHERE n.descr = 'Fluencia'");
        java.util.List<jpa.entities.Norma> normaListFluencia = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(normaQueryFluencia.getResultList());
        javax.persistence.Query normaQueryTraccion = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT n FROM Norma n WHERE n.descr = 'Traccion'");
        java.util.List<jpa.entities.Norma> normaListTraccion = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(normaQueryTraccion.getResultList());

        entityManager.persist(e);
        e.setTipoEnsayoIdTipoEnsayo(new TipoEnsayo((short) 1));
        e.setFecha(new Date());
        e.setNormaIdNormaFluencia(normaListFluencia.get(0));
        e.setNormaIdNormaTraccion(normaListTraccion.get(0));
        e.setLongitud(400);
        list.add(e);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));

        //Reiniciar componentes
        habilitarFormulario(true);
        btnConnect.setEnabled(true);
        saveButton.setEnabled(false);
        jButtonImprimir.setEnabled(false);
        newButton.setEnabled(false);
        jComboBoxDiametro.setEnabled(true);
        datoPiedeRey = "";
        datoCeldasActual = 0;
        datoPieDeRey = 0;
        traccion = 0;
        fluencia = 0;
        datos = new ArrayList<>();
        jTableCeldasPie.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{},
                new String[]{"Celdas", "Pie de Rey"}));
        //Grafica
        // create a dataset...
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        chart = createChart(dataset);
        // add chart to JPanel
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setSize(jPanelGrafica.getSize());
        jPanelGrafica.add(chartPanel);
//        jPanelGrafica.repaint();

    }

    public void impresion(String nombreJasper) {
        String idEnsayo;

        try {
            idEnsayo = idEnsayoField.getText();
            String ubicacion = System.getProperty("user.dir") + "/src/reportes/" + nombreJasper;
            //llamar el repote
            Reportes reporte = new Reportes();
            reporte.informe(logotipo, idEnsayo, ubicacion, normaIdNormaFluenciaField.getText(), normaIdNormaTraccionField.getText());
            // fin reporte

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }

    public void setDatoCeldas(String a) {
        try {
            a = a.replace(" ", "");
            datoCeldasTemp = datoCeldasActual;
            datoCeldasActual = Float.parseFloat(a);
        } catch (NumberFormatException ex) {
            System.err.println(ex.getMessage());
        }
    }

    public void actualizar() {
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
    }

    public void detener() {
        habilitarFormulario(true);
        saveButton.setEnabled(true);
        btnConnect.setEnabled(false);

        //Grafica
        CategoryDataset dataset = createDataset();
        LocalListener l = new LocalListener();
        chart.addChangeListener(l);
        CategoryPlot plot = (CategoryPlot) this.chart.getPlot();
        plot.setDataset(dataset);

        windows.paralelo.escribirEnPuerto((byte) 0, (String) cboxPorts1.getSelectedItem());

        windows.paralelo.cerrarPuerto();
//        float floatCorte = 0;
        if (!datos.isEmpty()) {
            traccion = datos.get(0).getCelda();
            int i = 0;
            for (Dato celda : datos) {
                i++;
                if (celda.getEsfuerzo() > traccion) {
                    traccion = celda.getEsfuerzo();
                    i = 0;
                }                
                if (i == 2){
                    fluencia = ((traccion + celda.getEsfuerzo())/2);
                }
            }
            //Fluencia
//            if (fluencia == traccion) {
//                boolean temp = false;
//                boolean corte = false;
//                Dato datoTemp = new Dato();
//                for (Dato celda : datos) {
//                    if (celda.getEsfuerzo() == traccion) {
//                        temp = true;       
//                        datoTemp = celda;
//                    }
//                    if (temp && celda.getEsfuerzo() <= (datoTemp.getEsfuerzo() - 20)) {
//                        floatCorte = datoTemp.getEsfuerzo();
//                    }
//                }
//            }
            traccionResistenciaField.setText(String.valueOf(df.format(traccion)));
            fluenciaResistenciaField.setText(String.valueOf(df.format(fluencia)));
            elongacionPorcentajeField.setText(String.valueOf(datos.get(datos.size() - 1).getElongacion()));
        }
    }

    public void habilitarFormulario(boolean habilitar) {
        //Deshabilitar componentes
        obraField.setEnabled(habilitar);
        jComboBoxCliente.setEnabled(habilitar);
        jComboBoxLaboratorista.setEnabled(habilitar);
        jComboBoxCertificacion.setEnabled(habilitar);
        jTextFieldLeerPieDeRey.setEnabled(!habilitar);

        refreshButton.setEnabled(habilitar);
        newButton.setEnabled(habilitar);
        jButtonDetener.setEnabled(!habilitar);
    }

    private void conectar() throws HeadlessException {
        if (jComboBoxDiametro.getSelectedItem() == null || longitudField.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Debe especificar el diametro y la longitud inicial");
        } else {
            jComboBoxDiametro.setEnabled(false);
            longitudField.setEnabled(false);
            elongacionPorcentajeField.setEnabled(false);
            btnConnect.setEnabled(false);
            habilitarFormulario(false);
            datos = new ArrayList<>();
            jTextFieldLeerPieDeRey.grabFocus();
            windows.communicator.connect((String) cboxPorts.getSelectedItem());
            if (windows.communicator.getConnected() == true) {
                if (windows.communicator.initIOStream() == true) {
                    windows.communicator.initListener();
                }
            }
            windows.paralelo.escribirEnPuerto((byte) 1, (String) cboxPorts1.getSelectedItem());
        }
    }

    private void leerDatos() {
        DefaultTableModel tableModelTemp = (DefaultTableModel) jTableCeldasPie.getModel();
        Float datoTemp;

        String temp = jTextFieldLeerPieDeRey.getText();
        temp = temp.replace("'", "-");
        try {
            datoTemp = Float.parseFloat(temp);
            if (datoTemp > 0) {
                if (datoTemp == datoPieDeRey) {
                    jTextFieldLeerPieDeRey.setText("");
                    detener();
                } else {
                    Dato dato = new Dato(Float.parseFloat(longitudField.getText()),
                            Float.parseFloat(jComboBoxDiametro.getSelectedItem().toString()), datoTemp, datoCeldasActual);
                    if (!booleanFluencia & datoCeldasActual < datoCeldasTemp) {
                        fluencia = (float) (datoCeldasTemp / (Math.PI * Math.pow((dato.getDiametro() / 2), 2)));
                        booleanFluencia = true;
                    }
                    datos.add(dato);
                    Object nuevaFila[] = {df.format(datoCeldasActual), df.format(datoTemp)};
                    tableModelTemp.addRow(nuevaFila);
                    datoPieDeRey = datoTemp;
                }
            }
        } catch (NumberFormatException ex) {
        }
        jTextFieldLeerPieDeRey.setText("");
    }

    private void guardar() throws HeadlessException {
        if (jComboBoxCliente.getSelectedItem() == null || jComboBoxLaboratorista.getSelectedItem() == null
                || jComboBoxDiametro.getSelectedItem() == null || jComboBoxCertificacion.getSelectedItem() == null
                || detalleField.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Los campos con * son requeridos");
        } else {
            try {
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();
                int index = masterTable.getSelectedRow();
                jpa.entities.Ensayo e = list.get(masterTable.convertRowIndexToModel(index));
                Collection<jpa.entities.GraficaEnsayo> gs = e.getGraficaEnsayoList();
                if (gs == null) {
                    gs = new LinkedList<>();
                    e.setGraficaEnsayoList((List) gs);
                }
                for (Dato dato : datos) {
                    jpa.entities.GraficaEnsayo g = new jpa.entities.GraficaEnsayo();
                    entityManager.persist(g);
                    g.setGraficaEnsayoPK(new GraficaEnsayoPK());
                    g.setEnsayo(e);
                    g.setDeformacion(dato.getDeformacion());
                    g.setEsfuerzo(dato.getEsfuerzo());
                    gs.add(g);
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                }

                actualizar();
                jButtonImprimir.setEnabled(true);
                newButton.setEnabled(true);
                saveButton.setEnabled(false);
                int row = list.size() - 1;
                masterTable.setRowSelectionInterval(row, row);
                masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
            } catch (RollbackException rex) {
                rex.printStackTrace();
                entityManager.getTransaction().begin();
                List<jpa.entities.Ensayo> merged = new ArrayList<>(list.size());
                for (jpa.entities.Ensayo e : list) {
                    merged.add(entityManager.merge(e));
                }
                list.clear();
                list.addAll(merged);
            }
        }
    }

    private JFreeChart createChart(CategoryDataset dataset) {

        // create the chart...
        JFreeChart chartInicial = ChartFactory.createLineChart(
                "Ensayo de Tracción", // chart title
                "Deformación %", // domain axis label
                "Esfuerzo Kg-f/mm²", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, // orientation
                false, // include legend
                true, // tooltips
                false // urls
                );

        // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
//        final StandardLegend legend = (StandardLegend) chart.getLegend();
        //      legend.setDisplaySeriesShapes(true);
//            legend.setShapeScaleX(1.5);
        //  legend.setShapeScaleY(1.5);
        //legend.setDisplaySeriesLines(true);

        chartInicial.setBackgroundPaint(Color.white);

        CategoryPlot plot = (CategoryPlot) chartInicial.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.white);

        // customise the range axis...
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        rangeAxis.setAutoRangeIncludesZero(true);
        return chartInicial;
    }

    /**
     * Creates a sample dataset.
     *
     * @return The dataset.
     */
    private CategoryDataset createDataset() {

        // row keys...
        String series1 = "Ensayo Tracción";

        // create the dataset...
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        for (Dato dato : datos) {
            dataset.addValue(dato.getEsfuerzo(), series1, String.valueOf(df.format(dato.getDeformacion())));
        }

        return dataset;
    }

    private void renderGrafico() {
        newButton.setEnabled(true);
        jButtonImprimir.setEnabled(true);
        btnConnect.setEnabled(false);

        int index = masterTable.getSelectedRow();
        jpa.entities.Ensayo e = list.get(masterTable.convertRowIndexToModel(index));
        Collection<jpa.entities.GraficaEnsayo> gs = e.getGraficaEnsayoList();

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        for (GraficaEnsayo i : gs) {
            dataset.addValue(i.getEsfuerzo(), "Prueba Tracción", String.valueOf(df.format(i.getDeformacion())));
        }
        //Grafica

        LocalListener l = new LocalListener();
        chart.addChangeListener(l);
        CategoryPlot plot = (CategoryPlot) this.chart.getPlot();
        plot.setDataset(dataset);
//
    }

    /**
     * A chart change listener.
     *
     */
    static class LocalListener implements ChartChangeListener {

        /**
         * A flag.
         */
        private boolean flag = false;

        /**
         * Event handler.
         *
         * @param event the event.
         */
        public void chartChanged(ChartChangeEvent event) {
            this.flag = true;
        }
    }
}
